/*
 * Copyright [2022] [liufeng]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.f.service.impl;

import com.f.bo.IdReasonBo;
import com.f.bo.flow.FlowStartProcessBo;
import com.f.client.FlowClient;
import com.f.constant.Constant;
import com.f.entity.LeaveApply;
import com.f.enums.flow.FlowStatus;
import com.f.mapper.LeaveApplyMapper;
import com.f.service.BaseServiceImpl;
import com.f.service.LeaveApplyService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 * 请假申请 服务实现类
 * </p>
 *
 * @author liuf
 * @date 2022-12-22
 */
@RequiredArgsConstructor
@Service
public class LeaveApplyServiceImpl extends BaseServiceImpl<LeaveApplyMapper, LeaveApply> implements LeaveApplyService {

    private static final Logger LOGGER = LoggerFactory.getLogger(LeaveApplyServiceImpl.class);

    private final FlowClient flowClient;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public LeaveApply insert(LeaveApply entity) {
        entity.setStatus(FlowStatus.NOT_COMMIT.getStatus());
        return super.insert(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String commit(String id) {
        LOGGER.info("commit:{}", id);
        LeaveApply leaveApply = new LeaveApply();
        leaveApply.setId(Long.parseLong(id));
        leaveApply.setStatus(FlowStatus.COMMIT.getStatus());
        LOGGER.info("启动流程");
        Map<String, Object> map = new HashMap<>(8);
        map.put(Constant.FLOW_SERVICE, "leaveApplyClient");
        String processId = flowClient.start(new FlowStartProcessBo().setKey(LeaveApply.class.getSimpleName())
                .setBusinessKey(id + "")
                .setVariables(map));
        leaveApply.setProcessId(processId);
        update(leaveApply);
        return processId;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unCommit(String id) {
        LeaveApply apply = getById(Long.parseLong(id));
        if (apply == null || FlowStatus.COMMIT.getStatus() != Optional.ofNullable(apply.getStatus()).orElse(0)) {
            return;
        }
        flowClient.delete(new IdReasonBo(id, "流程撤回"));
        apply.setStatus(FlowStatus.NOT_COMMIT.getStatus());
        update(apply);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void taskCompleted(String id) {
        LeaveApply apply = getById(Long.parseLong(id));
        if (apply == null || FlowStatus.COMMIT.getStatus() != Optional.ofNullable(apply.getStatus()).orElse(0)) {
            return;
        }
        LOGGER.info("流程审核中");
        apply.setStatus(FlowStatus.AUDITING.getStatus());
        update(apply);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void processCompleted(String id, String status) {
        LeaveApply apply = getById(Long.parseLong(id));
        if (apply == null || FlowStatus.SUCCESS.getStatus() == Optional.ofNullable(apply.getStatus()).orElse(0)) {
            return;
        }
        if (Constant.FLOW_APPROVE.equals(status)) {
            apply.setStatus(FlowStatus.SUCCESS.getStatus());
        } else {
            apply.setStatus(FlowStatus.REJECT.getStatus());
        }
        update(apply);
    }
}
